<template>
  <div class="container-fluid m-0 p-0">
    <!-- 圆角边框样式 -->
    <div class="radius" :style="{ borderRadius: 'var(--el-border-radius-base)' }">
      <el-row>
        <el-col :span="5">
          <!-- 科室名称下拉框 -->
          <div>
            <el-form>
              <el-form-item label="所属科室" style="padding-top: 5%;width: 220px; margin-left: 10px;">
                <el-select placeholder="所属科室" :model="deptIdOption">
                  <el-option style="max-width: 220px;" :label="row.label"  :value="row.value" v-for="(row,index) in deptList" :key="index" />
                </el-select>
              </el-form-item>
              <!--         <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属部门"
            :data="deptList"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item> -->
            </el-form>
          </div>
        </el-col>
        <el-col :span="5">
          <!-- 医生名称下拉框 -->
          <div>
            <el-form>
              <el-form-item label="医生名称" style="padding-top: 5%;width: 220px; margin-left: 10px;">
                <el-select placeholder="医生名称">
                  <el-option style="max-width: 220px;" label="Zone one" value="shanghai" />
                  <el-option label="Zone two" value="beijing" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <!-- 搜索按钮和重置按钮 -->
        <el-col :span="5">
          <div style="padding-top: 5%;width: 220px; margin-left: 0px;">
            <el-button type="primary" :icon="Search">搜索</el-button>
            <el-button type="primary"><el-icon>
                <Refresh />
              </el-icon>重置</el-button>
          </div>
        </el-col>
        <el-col :span="9">
          <div style="padding-top: 2.5%;">
            <el-button type="primary" :icon="Plus" @click="PrevWeekMonday">上一周</el-button>
            <el-button type="success" @click="currentWeek"><el-icon>
                <Operation />
              </el-icon>当前周</el-button>
            <el-button type="primary" @click="nextWeek"><el-icon><Select /></el-icon>下一周</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 这周日期 -->
      <el-row>
        <el-col :span="24">
          <div class="radius" :style="{ borderRadius: 'var(--el-border-radius-base)' }">
            <div style="text-align: center;padding-top: 11px;">
              <span>{{ formatDateWithWeek(monday) }}</span>&nbsp;至&nbsp;
              <span>{{ formatDateWithWeek(sunday) }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <div class="radius" :style="{ borderRadius: 'var(--el-border-radius-base)' }" style="width: 90%;">
        <!-- 修改后的表格 -->
        <el-table :data="tableData" border style="width: 100%; margin-top: 20px;" :span-method="spanMethod">

          <!-- 医生列（合并行） -->
          <el-table-column prop="doctorName" label="医生" align="center" width="120" />

          <!-- 科室列（合并行） -->
          <el-table-column prop="deptName" label="科室" align="center" width="120" />

          <!-- 时段列 -->
          <el-table-column prop="timeSlot" label="时间/日期" align="center" width="100" />

          <!-- 动态日期列 -->
          <el-table-column v-for="(day, index) in days" :key="index" :label="formatDateWithWeek(day)" align="center"
            width="120">
            <template #default="scope">
              <!-- 添加排班类型映射 -->
              <span v-if="scope.row.schedules[day] === '1'">门诊</span>
              <span v-else-if="scope.row.schedules[day] === '2'">急诊</span>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <!-- 操作列（合并行） -->
          <el-table-column label="操作" align="center" width="100" aria-colspan="3">
            <template #default="scope">
              <!-- 只在每行的第一时段显示操作按钮 -->
              <el-button size="small" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 编辑模态框 -->
    <div>
      <el-dialog v-model="centerDialogVisible" width="66%" align-center>
        <h1>修改【<span>{{ doctorNameScheduling }}</span>】排班</h1>
        <el-table :data="tableDataUpdate" border style="width: 100%; margin-top: 20px;">
          <!-- 时段列 -->
          <el-table-column label="时间/日期" width="120">
            <template #default="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <!-- 修改模态框中的表格列 -->
          <el-table-column v-for="(day, index) in days" :key="index" :label="formatDateWithWeek(day)">
            <template #default="scope">
              <!-- 修改：绑定到当前行当前日期的值 -->
              <el-select v-model="scope.row.values[day]" placeholder="请选择"
                @change="handleSelectionChange(scope.row, day)">
                <el-option v-for="option in scheduling_type" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>

        <template #footer>

        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { useCssVar } from '@vueuse/core'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  Operation,
  Select,
  Refresh
} from '@element-plus/icons-vue'
import type { TableColumnCtx } from 'element-plus'
import { onMounted, ref, reactive, computed } from 'vue'
import { getDate, getWeekMonday, getWeekSunday, formatDate,getPrevWeek,getNextWeek } from '@/api/doctor/Date/DateNew'
//获取医生排班数据
import { getScheduling, setScheduling } from '@/api/doctor/scheduling'
//获取字典时段数据
import { getDictOptions } from '@/api/system/dict'
import { get } from 'lodash'
import { Scheduling } from '@/api/doctor/scheduling/type'
import { getDeptOptions } from '@/api/system/dept'
const centerDialogVisible = ref(false)//控制编辑模态框
let time_type = ref([])
let scheduling_type = ref([])
let selectedValue = ref([])
//科室id
let deptIdOption=ref()
//获取所属科室getRoleOptions
const deptList = ref<OptionType[]>(); // 部门下拉数据源
/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}
//获取字典中的挂号类型[]
function getDictFormData2(dict_type = '') {
  getDictOptions(dict_type).then((response) => {
    console.log(response.data)
    const time_typeOptions = response.data;
    let ObjectList = ref([])
    time_typeOptions.forEach(response => {
      ObjectList.value.push(response)
      console.log("Object" + response.label)
      scheduling_type.value = ObjectList.value;
    });
  })
}
const PrevWeekMonday = () => {
  monday.value = getPrevWeekMonday()
  sunday.value = getPrevWeekSunday()
  days.value = generateWeekDays(new Date(monday.value)) // 更新日期数组
  console.log(days.value)
  getSchedulingPage()
}
// 当前周功能
const currentWeek = () => {
  monday.value = formatDate(getWeekMonday())
  sunday.value = formatDate(getWeekSunday())
  days.value = generateWeekDays(new Date()) // 更新日期数组
  getSchedulingPage()
}
// 下一周功能
const nextWeek = () => {
  monday.value = getNextWeekMonday()
  sunday.value = getNextWeekSunday()
  days.value = generateWeekDays(new Date(monday.value)) // 更新日期数组
  getSchedulingPage()
}
// 添加日期工具函数
const getPrevWeekMonday = () => {
  const prevMonday = new Date(monday.value);
  prevMonday.setDate(prevMonday.getDate() - 7);
  return formatDate(prevMonday);
};

const getNextWeekMonday = () => {
  const nextMonday = new Date(monday.value);
  nextMonday.setDate(nextMonday.getDate() + 7);
  return formatDate(nextMonday);
};

const getPrevWeekSunday = () => {
  const prevSunday = new Date(sunday.value);
  prevSunday.setDate(prevSunday.getDate() - 7);
  return formatDate(prevSunday);
};

const getNextWeekSunday = () => {
  const nextSunday = new Date(sunday.value);
  nextSunday.setDate(nextSunday.getDate() + 7);
  return formatDate(nextSunday);
};

//获取字典数据时段
function getDictFormData(dict_type = '') {
  let ObjectList = ref([])
  getDictOptions(dict_type).then((response) => {
    console.log(response.data)
    const time_typeOptions = reactive(response.data);
    time_typeOptions.forEach(response => {
      ObjectList.value.push(response)
      time_type.value = ObjectList.value;
      console.log("Object" + response.label)
    });
  })
  return ObjectList;
}
// 定义API返回的数据结构
interface ApiResponse {
  code: string
  data: {
    list: DoctorScheduling[]
    total: number
  }
  msg: string
}

// 定义医生排班数据结构，适配API返回格式
interface DoctorScheduling {
  userId: string
  userName: string
  deptId: string
  deptName: string
  schedules: Record<string, Record<number, string>> // 格式: { "2025-05-29": {1: "1", 2: "1"} }
}

// 使用ref创建响应式数据
const apiData = ref<ApiResponse | null>(null)
const tableData = ref<any[]>([]) // 存储重构后的表格数据

// 生成当前周的日期数组
// 生成当前周的日期数组
const generateWeekDays = (date: Date) => {
  console.log("B")
  console.log(date)
  const daysArray = []
  const currentMonday = getWeekMonday(date)
  for (let i = 0; i < 7; i++) {
    const dayDate = new Date(currentMonday) // 重命名变量避免冲突
    dayDate.setDate(dayDate.getDate() + i)
    daysArray.push(formatDate(dayDate)) // 格式化为 YYYY-MM-DD
  }
  return daysArray
}

// 初始化 days 为数组
const days = ref(generateWeekDays(new Date()))
const monday = ref(formatDate(getWeekMonday()))
const sunday = ref(formatDate(getWeekSunday()))

// 添加日期格式化函数（显示星期）
const formatDateWithWeek = (dateStr: string) => {
  const date = new Date(dateStr)
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const weekDay = weekDays[date.getDay()]
  return `${date.getFullYear()}-${month}-${day}(周${weekDay})`
}
const tableDataUpdate = ref<any[]>([])
//定义分页遍历
let pageNum=ref(1)
let pageSize=ref(100)
onMounted(() => {
  //加载部门下拉框资源
  loadDeptOptions();
  // 获取时段
  getDictFormData('time_type')
  getDictFormData2('scheduling_type')
  // 调用查询医生排班数据api接口
  getScheduling({ monday: monday.value, sunday: sunday.value,pageSize:pageSize.value,pageNum:pageNum.value }).then(response => {
    apiData.value = response

    // ===== 重构表格数据 =====
    const tempData: any[] = []

    if (apiData.value?.data.list) {
      apiData.value.data.list.forEach(doctor => {
        // 为每个医生创建三个时段的数据行
        ['上午', '下午', '晚上'].forEach(timeSlot => {
          // 确定排班类型键值
          const timeSlotKey = timeSlot === '上午' ? 1 :
            timeSlot === '下午' ? 2 : 3;

          tempData.push({
            userId: doctor.userId,
            doctorName: doctor.userName,
            deptName: doctor.deptName,
            timeSlot: timeSlot,
            deptId: doctor.deptId,
            schedules: days.value.reduce((acc, day) => {
              // 获取该日期该时段的排班状态
              const schedule = doctor.schedules[day]
              acc[day] = schedule?.[timeSlotKey] || null
              return acc
            }, {} as Record<string, string | null>)
          })
        })
      })
    }

    tableData.value = tempData
    console.log("重构后的表格数据:", tableData.value)
  }).catch(error => {
    console.error('获取医生排班数据失败', error)
  })
})
//封装表格查询方法
function getSchedulingPage() {
  getScheduling({
    monday: monday.value,
    sunday: sunday.value,
    pageSize: pageSize.value,
    pageNum: pageNum.value
  }).then(response => {
    apiData.value = response
    const tempData: any[] = []

    if (apiData.value?.data.list) {
      apiData.value.data.list.forEach(doctor => {
        ['上午', '下午', '晚上'].forEach(timeSlot => {
          const timeSlotKey = timeSlot === '上午' ? 1 :
            timeSlot === '下午' ? 2 : 3;

          tempData.push({
            userId: doctor.userId,
            doctorName: doctor.userName,
            deptName: doctor.deptName,
            timeSlot: timeSlot,
            deptId: doctor.deptId,
            // 使用 reduce 正确构建 schedules 对象
            schedules: days.value.reduce((acc, day) => {
              const schedule = doctor.schedules[day]
              acc[day] = schedule?.[timeSlotKey] || null
              return acc
            }, {} as Record<string, string | null>)
          })
        })
      })
    }

    tableData.value = tempData
  }).catch(error => {
    console.error('获取医生排班数据失败', error)
  })
}
// 单元格合并方法（优化版）
const spanMethod = ({ row, column, rowIndex }: { row: any, column: any, rowIndex: number }) => {
  const mergeCols = ['doctorName', 'deptName']
  const prop = column.property

  // 需要合并的列医生和科室列的合并逻辑
  if (mergeCols.includes(prop)) {
    // 只在每个医生的第一行（上午）显示
    if (row.timeSlot === '上午') {
      return { rowspan: 3, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 } // 其他行不显示
    }
  }
  if (prop === undefined && column.label === '操作') {
    if (row.timeSlot == '上午') {
      return {
        rowspan: 3,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }

  // 操作列已在模板中处理，这里不需要额外逻辑
  return { rowspan: 1, colspan: 1 }
}

// 编辑处理函数
const handleUpdate = (row: any) => {
  console.log(row + "<A")
  scheduleling.value.userId = row.userId
  scheduleling.value.userName = row.userName
  scheduleling.value.deptName = row.deptName
  scheduleling.value.deptId = row.deptId
  console.log("编辑医生排班:", row)
  doctorNameScheduling.value = row.doctorName
  centerDialogVisible.value = true



  // 初始化编辑数据
  tableDataUpdate.value = [
    {
      title: '上午',
      timeSlot: 1,
      values: {} // 存储每个日期的值
    },
    {
      title: '下午',
      timeSlot: 2,
      values: {}
    },
    {
      title: '晚上',
      timeSlot: 3,
      values: {}
    }
  ]
  // 获取最新排班数据
  getScheduling({
    monday: monday.value,
    sunday: sunday.value,
    deptId: row.deptId,
    doctorId: row.userId,
    pageSize:pageSize.value,
    pageNum:pageNum.value
  }).then(response => {
    // 提取医生的排班数据
    const doctorData = response.data.list.find((d: any) => d.userId === row.userId);
    if (!doctorData) return;

    const schedules = doctorData.schedules;

    // 填充数据到编辑表格
    days.value.forEach(day => {
      tableDataUpdate.value.forEach(timeSlotRow => {
        const timeSlotKey = timeSlotRow.timeSlot;
        // 获取排班值（1/2/空）
        const scheduleValue = schedules[day]?.[timeSlotKey] || '';
        timeSlotRow.values[day] = scheduleValue;
      });
    });

    console.log("填充后的编辑数据:", tableDataUpdate.value);
  }).catch(error => {
    console.error('获取医生排班数据失败', error);
    // 失败时使用原始数据
    days.value.forEach(day => {
      tableDataUpdate.value.forEach(timeSlotRow => {
        const timeSlotKey = timeSlotRow.timeSlot;
        timeSlotRow.values[day] = row.schedules[day]?.[timeSlotKey] || '';
      });
    });
  });

  // 填充当前医生的排班数据
  days.value.forEach(day => {
    tableDataUpdate.value.forEach(timeSlotRow => {
      // 从原始数据获取当前时段的值
      const timeSlotKey = timeSlotRow.timeSlot
      const originalValue = row.schedules[day]?.[timeSlotKey] || ''

      // 初始化每个单元格的值
      timeSlotRow.values[day] = originalValue
    })
  })

  console.log("初始化编辑数据:", tableDataUpdate.value)
}

//定义排班对象
let scheduleling = ref({
  userId: 0,
  userName: '',
  deptName: '',
  deptId: 0,
  schedulingDay: '',
  subsectionType: -1,
  schedulingType: '',
  createTime: formatDate(new Date),
  createBy: ''
})

//处理编辑下拉框选择事件
const handleSelectionChange = (row: any, day: string) => {
  //循环遍历
  // 遍历values对象
  Object.keys(row.values).forEach(date => {
    const value = row.values[date];
    console.log(`日期: ${date}, 值: ${value}`);
    // 这里可以添加你的处理逻辑
    if (value != "") {
      // 示例：特殊处理
      console.log(`找到有效数据: ${date}`);
      console.log(row)
      scheduleling.value.schedulingType = value
      scheduleling.value.subsectionType = row.timeSlot
      scheduleling.value.schedulingDay = date
      console.log(scheduleling.value.subsectionType + "ACACC")
      console.log(scheduleling.value.userId + "ACACCV")
      setScheduling(scheduleling.value)

    }

  });

  // 可以在这里添加处理逻辑
  console.log("选择变更", row, day);

}
//监听centerDialogVisible编辑模态框
watch(centerDialogVisible, (New, Old) => {
  console.log('新值:', New)
  console.log('新值:', Old)
  //  当用户关闭修改模态框的时候更新表格数据
  if (!New) {
    getScheduling({ monday: monday.value, sunday: sunday.value,pageSize:pageSize.value,pageNum:pageNum.value }).then(response => {
      apiData.value = response

      // ===== 重构表格数据 =====
      const tempData: any[] = []

      if (apiData.value?.data.list) {
        apiData.value.data.list.forEach(doctor => {
          // 为每个医生创建三个时段的数据行
          ['上午', '下午', '晚上'].forEach(timeSlot => {
            // 确定排班类型键值
            const timeSlotKey = timeSlot === '上午' ? 1 :
              timeSlot === '下午' ? 2 : 3;

            tempData.push({
              userId: doctor.userId,
              doctorName: doctor.userName,
              deptName: doctor.deptName,
              timeSlot: timeSlot,
              deptId: doctor.deptId,
              schedules: days.value.reduce((acc, day) => {
                // 获取该日期该时段的排班状态
                const schedule = doctor.schedules[day]
                acc[day] = schedule?.[timeSlotKey] || null
                return acc
              }, {} as Record<string, string | null>)
            })
          })
        })
      }

      tableData.value = tempData
      console.log("重构后的表格数据:", tableData.value)
    }).catch(error => {
      console.error('获取医生排班数据失败', error)
    })
  }
})
//定义双向绑定变量
let doctorNameScheduling = ref('')
</script>

<style scoped>
/* 添加表头分组样式 */
:deep(.el-table__header) tr th {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 调整行高 */
:deep(.el-table__row) td {
  padding: 8px 0;
  height: 50px;
}

.title {
  color: var(--el-text-color-regular);
  font-size: 18px;
  margin: 10px 0;
}

.value {
  color: var(--el-text-color-primary);
  font-size: 16px;
  margin: 10px 0;
}

.radius {
  height: 60px;
  border: 1px solid var(--el-border-color);
  margin-top: 20px;
  background-color: white;
  width: 90%;
  margin: 10px auto;
}
</style>
